package cn.kgc.login.dao;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Repository;

import java.util.Map;
import java.util.Set;
import java.util.concurrent.TimeUnit;

/**
 * Created by teacher ZHANG on 2022/12/5
 */
@Repository
public class RedisDaoImpl implements RedisDao {
    @Autowired
    private StringRedisTemplate redisTemplate;

    @Override
    public void hashSet(String key, Map<String, String> value) {
        redisTemplate.opsForHash().putAll(key, value);
    }

    @Override
    public Map<Object, Object> hashGet(String key) {
        return redisTemplate.opsForHash().entries(key);
    }

    @Override
    public Boolean keyExist(String key) {
        return redisTemplate.hasKey(key);
    }

    //根据pattern样式取所有的键名
    @Override
    public Set<String> keys(String pattern) {
        return redisTemplate.keys(pattern);
    }

    //设置过期时间
    @Override
    public void setExpire(String key, Integer secs) {
        redisTemplate.expire(key, secs, TimeUnit.SECONDS);
    }

    @Override
    public Integer getExpire(String key) {
        return redisTemplate.getExpire(key, TimeUnit.SECONDS).intValue();
    }

    @Override
    public void strSet(String key, String value, Integer secs) {
        if (secs > 0) {
            redisTemplate.opsForValue().set(key, value, secs, TimeUnit.SECONDS);
        }
        else {
            redisTemplate.opsForValue().set(key, value);
        }
    }

    @Override
    public String strGet(String key) {
        return redisTemplate.opsForValue().get(key);
    }
}
